<template>
    <div class="login-container">
      <div class="login-box">
        <div class="logo-area">
          <img src="../../../../public/780.png" alt="Logo">
        </div>
        <div class="form-area">
          <h2>ESM平台</h2>
      <el-form 
            ref="loginFormRef" 
            :model="formData" 
            :rules="formRules" 
            @submit.prevent="handleLogin"
          >
            <!-- 用户名 -->
            <el-form-item prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入账号"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>
            
            <!-- 密码 -->
            <el-form-item prop="password">
              <el-input
                v-model="formData.password"
                placeholder="请输入密码"
                type="password"
                show-password
                :prefix-icon="Lock"
                clearable
              />
            </el-form-item>
            
            <!-- 验证码 -->
            <el-form-item prop="captcha">
              <div class="captcha-container">
                <el-input
                  v-model="formData.captcha"
                  placeholder="验证码"
                  :prefix-icon="Key"
                  clearable
                  style="width: 60%"
                />
                <div class="captcha-box" @click="refreshCaptcha">
                  <span 
                    v-for="(char, index) in captcha" 
                    :key="index" 
                    :style="getCharStyle(index)"
                  >
                    {{ char }}
                  </span>
                </div>
              </div>
            </el-form-item>
            
            <!-- 记住我 -->
            <el-form-item>
              <el-checkbox-group v-model="rememberOptions">
                <el-checkbox :label="1">记住账号</el-checkbox>
                <el-checkbox :label="2">记住密码</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <!-- 登录按钮 -->
            <el-form-item>
              <el-button 
                type="primary" 
                native-type="submit" 
                :loading="loading"
                style="width: 100%"

              >
                登录
              </el-button>
            </el-form-item>
            
            <!-- 消息提示 -->
            <el-alert
              v-if="message"
              :title="message"
              :type="alertType"
              show-icon
              closable
               @close="message = ''"
            />
            
          </el-form>
          <div class="register-link"> 
            <router-link to="./register"> 注册账号</router-link>
          </div>
        </div>
      </div>
    </div>
</template>

<script setup>
import { ref, onMounted,computed} from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {user_Login} from '../../http/user'
import userStore  from '../../store/userStore'

const user_s=userStore()

const router = useRouter()
  // 表单数据
  const formData = ref({
    username: '',
    password: '',
    captcha: ''
  })
  
  // 记住我选项
  const rememberOptions = ref([])
  
  // 验证码
  const captcha = ref(generateCaptcha())
  const message = ref('')
  const loading = ref(false)
  const loginFormRef = ref(null)
  
  // 计算属性用于确定警告类型
const alertType = computed(() => {
  return message.value.includes('成功') ? 'success' : 'error'
})
  // 表单验证规则
  const formRules = {
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' },
      { min: 3, max: 16, message: '长度在3到16个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
    ],
    captcha: [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { validator: validateCaptcha, trigger: 'blur' }
    ]
  }
  
  // 生成验证码
  function generateCaptcha() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
    let result = ''
    for (let i = 0; i < 4; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }
  
  // 刷新验证码
  function refreshCaptcha() {
    captcha.value = generateCaptcha()
    formData.value.captcha = ''
  }
  
  // 验证码验证
  function validateCaptcha(rule, value, callback) {
    if (!value) {
      callback(new Error('请输入验证码'))
    } else if (value.toLowerCase() !== captcha.value.toLowerCase()) {
      callback(new Error('验证码不正确'))
      refreshCaptcha()
    } else {
      callback()
    }
  }
  
  // 获取字符样式
  function getCharStyle(index) {
    return {
      transform: `rotate(${Math.random() * 20 - 10}deg)`,
      color: `hsl(${Math.random() * 360}, 70%, 50%)`,
      fontSize: `${18 + Math.random() * 8}px`,
      display: 'inline-block',
      margin: '0 2px',
    }
  }
  
 // 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    loading.value = true
    
    // 验证表单
    await loginFormRef.value.validate()
    
    // 处理记住我选项
    if (rememberOptions.value.includes(1)) {
      localStorage.setItem('savedUsername', formData.value.username)
    } else {
      localStorage.removeItem('savedUsername')
    }
    
    if (rememberOptions.value.includes(2)) {
      localStorage.setItem('savedPassword', formData.value.password)
    } else {
      localStorage.removeItem('savedPassword')
    }
    
    // 调用登录API - 保持与你API一致的两个参数形式
    const result = await user_Login(
      formData.value.username,
      formData.value.password
    )
    
    if (result.data?.sessionToken) {
      ElMessage.success('登录成功')
      localStorage.setItem('token', result.data.sessionToken)
      user_s.setToken(result.data.sessionToken)
      user_s.setUsername(formData.value.username)

      router.push('/home')
    } else {
      const errorMsg = result.data?.message || '登录失败，请检查账号密码'
      ElMessage.error(errorMsg)
      refreshCaptcha()
    }
  } catch (error) {
    console.error('登录错误:', error)
    let errorMsg = '登录失败，请稍后重试'
    
    if (error.response) {
      // HTTP错误
      errorMsg = error.response.data?.message || errorMsg
    } else if (error.message) {
      // 验证错误
      errorMsg = error.message
    }
    
    ElMessage.error(errorMsg)
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 初始化记住的账号密码
onMounted(() => {
  const savedUsername = localStorage.getItem('savedUsername')
  const savedPassword = localStorage.getItem('savedPassword')
  
  if (savedUsername) {
    formData.value.username = savedUsername
    rememberOptions.value.push(1)
  }
  
  if (savedPassword) {
    formData.value.password = savedPassword
    rememberOptions.value.push(2)
  }
})
</script>
  
<style lang="scss" scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100vh;
    background: url('../../../../public/bg.jpg') no-repeat center center;
    background-size: cover;
  }
  .login-box {
    display: flex;
    width: 900px;
    height: 500px;
    background: rgba(255, 255, 255, 0.85);
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
  .logo-area {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background: linear-gradient(135deg, #b692df, #6a5acd);
    
    img {
      width: 70%;
      height: auto;
    }
  }
  
  .form-area {
    flex: 1;
    padding: 40px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    
    h2 {
      text-align: center;
      margin-bottom: 30px;
      color: #6a5acd;
      font-size: 28px;
    }
  }

  .captcha-container {
    display: flex;
    gap: 10px;
    align-items: center;
  }
  
  .captcha-box {
    flex: 1;
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f5f5f5;
    border-radius: 4px;
    cursor: pointer;
    user-select: none;
    transition: all 0.3s;
    
    &:hover {
      background: #e8e8e8;
    }
  }
  
  .el-alert {
    margin-top: 20px;
  }
  .router-link-active {
  text-decoration: none;
  color: #9dcdf5;
}
a {
  text-decoration: none;
  color: #9dcdf5;
}

</style>../../../http/user../../../store/userStore